package cn.uniquesoft.controller;

import cn.uniquesoft.controller.base.BaseController;
import cn.uniquesoft.manager.ClientManager;
import cn.uniquesoft.service.IArticleService;
import cn.uniquesoft.service.IPushMessageService;
import cn.uniquesoft.service.api.ILectureService;
import cn.uniquesoft.vo.AjaxResult;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.ArticleVO;
import cn.uniquesoft.vo.PushMessageVO;
import cn.uniquesoft.vo.RoleVO;
import cn.uniquesoft.vo.UserVO;
import cn.uniquesoft.vo.api.LectureVO;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.push.model.v20160801.PushRequest;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.aliyuncs.utils.ParameterHelper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

/**
 * @创建人名 zjn
 * @创建日期 2017-11-01 14:25:30
 * @文件描述 控制器
 */

@Controller
@SuppressWarnings("unused")
@RequestMapping(value = "/pushmessage")
public class PushMessageController extends BaseController<PushMessageVO> {
    @Autowired
    private IPushMessageService pushmessageService;
    @Autowired
    private ILectureService lectureService;
    @Autowired
    private IArticleService iArticleService;
    private static Logger Log = LoggerFactory.getLogger(PushMessageController.class);
    @Autowired
    public PushMessageController(IPushMessageService pushmessageService) {
        super();
        this.baseService = pushmessageService;
        this.pushmessageService = pushmessageService;
        this.viewPath = "/mgr/pushmessage";
        this.viewName = "";
    }
    protected static String region;
    protected static long appKey;
    protected static String deviceIds;
    protected static String deviceId;
    protected static String accounts;
    protected static String account;
    protected static String aliases;
    protected static String alias;
    protected static String tag;
    protected static String tagExpression;

    protected static DefaultAcsClient client;

    /**
     * 从配置文件中读取配置值，初始化Client
     * <p>
     * 1. 如何获取 accessKeyId/accessKeySecret/appKey 照见README.md 中的说明<br/>
     * 2. 先在 push.properties 配置文件中 填入你的获取的值
     */

    // 添加数据
    @RequestMapping(value = "/addItem", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addItem(PushMessageVO item) {
//		ModelAndView result = new ModelAndView(this.viewPath+"index");
        AjaxResult ajaxResult = new AjaxResult();

        try {
            InputStream inputStream = PushMessageController.class.getClassLoader().getResourceAsStream("push.properties");
            Properties properties = new Properties();
            properties.load(inputStream);

            String accessKeyId = properties.getProperty("accessKeyId");

            String accessKeySecret = properties.getProperty("accessKeySecret");

            String key = properties.getProperty("appKey");

            region = properties.getProperty("regionId");
            appKey = Long.valueOf(key);
            deviceIds = properties.getProperty("deviceIds");
            deviceId = properties.getProperty("deviceId");
            accounts = properties.getProperty("accounts");
            account = properties.getProperty("account");
            aliases = properties.getProperty("aliases");
            alias = properties.getProperty("alias");
            tag = properties.getProperty("tag");
            tagExpression = properties.getProperty("tagExpression");

            IClientProfile profile = DefaultProfile.getProfile(region, accessKeyId, accessKeySecret);
            client = new DefaultAcsClient(profile);
            PushRequest pushRequest = new PushRequest();
            //安全性比较高的内容建议使用HTTPS
            pushRequest.setProtocol(ProtocolType.HTTPS);
            //内容较大的请求，使用POST请求
            pushRequest.setMethod(MethodType.POST);
            // 推送目标
            pushRequest.setAppKey(appKey);
            pushRequest.setTarget("ALL"); //推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
            pushRequest.setTargetValue("ALL"); //根据Target来设定，如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
//        pushRequest.setTarget("ALL"); //推送目标: device:推送给设备; account:推送给指定帐号,tag:推送给自定义标签; all: 推送给全部
//        pushRequest.setTargetValue("ALL"); //根据Target来设定，如Target=device, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
            pushRequest.setPushType(item.getCtype()); // 消息类型 MESSAGE NOTICE
            pushRequest.setDeviceType(item.getCdevicetype()); // 设备类型 ANDROID iOS ALL.


            // 推送配置
            pushRequest.setTitle(item.getCtitle()); // 消息的标题
            pushRequest.setBody(item.getCbody()); // 消息的内容

            /*// 推送配置: iOS
            pushRequest.setiOSBadge(5); // iOS应用图标右上角角标
            pushRequest.setiOSSilentNotification(false);//开启静默通知
            pushRequest.setiOSMusic("default"); // iOS通知声音
            pushRequest.setiOSSubtitle("iOS10 subtitle");//iOS10通知副标题的内容
            pushRequest.setiOSNotificationCategory("iOS10 Notification Category");//指定iOS10通知Category
            pushRequest.setiOSMutableContent(true);//是否允许扩展iOS通知内容
            pushRequest.setiOSApnsEnv("DEV");//iOS的通知是通过APNs中心来发送的，需要填写对应的环境信息。"DEV" : 表示开发环境 "PRODUCT" : 表示生产环境
            pushRequest.setiOSRemind(true); // 消息推送时设备不在线（既与移动推送的服务端的长连接通道不通），则这条推送会做为通知，通过苹果的APNs通道送达一次。注意：离线消息转通知仅适用于生产环境
            pushRequest.setiOSRemindBody("iOSRemindBody");//iOS消息转通知时使用的iOS通知内容，仅当iOSApnsEnv=PRODUCT && iOSRemind为true时有效
            pushRequest.setiOSExtParameters("{\"_ENV_\":\"DEV\",\"k2\":\"v2\"}"); //通知的扩展属性(注意 : 该参数要以json map的格式传入,否则会解析出错)*/
            // 推送配置: Android
            pushRequest.setAndroidNotifyType("NONE");//通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音
            pushRequest.setAndroidNotificationBarType(1);//通知栏自定义样式0-100
            pushRequest.setAndroidNotificationBarPriority(1);//通知栏自定义样式0-100
            /*pushRequest.setAndroidOpenType("URL"); //点击通知后动作 "APPLICATION" : 打开应用 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转
            pushRequest.setAndroidOpenUrl("http://www.baidu.com"); //Android收到推送后打开对应的url,仅当AndroidOpenType="URL"有效
            pushRequest.setAndroidActivity("com.alibaba.push2.demo.XiaoMiPushActivity"); // 设定通知打开的activity，仅当AndroidOpenType="Activity"有效*/
            pushRequest.setAndroidMusic("default"); // Android通知音乐
//            pushRequest.setAndroidXiaoMiActivity("com.ali.demo.MiActivity");//设置该参数后启动小米托管弹窗功能, 此处指定通知点击后跳转的Activity（托管弹窗的前提条件：1. 集成小米辅助通道；2. StoreOffline参数设为true）
            /*pushRequest.setAndroidXiaoMiNotifyTitle(item.getCtitle());//标题
            pushRequest.setAndroidXiaoMiNotifyBody(item.getCbody());//内容*/
//            pushRequest.setTitle(item.getCtitle());
//            pushRequest.setBody(item.getCbody());
//            LectureVO lectureVO = this.lectureService.fechOneByIid(item.getIlinkid());
//            pushRequest.setAndroidExtParameters("{\"url\":\""+lectureVO.getCurl()+"\",\"type\":\""+lectureVO.getCtype()+"\",\"videourl\":\""+lectureVO.getCvideourl()+"\",\"coverimg\":\""+lectureVO.getCoverimg()+"\",\"csummary\":\""+lectureVO.getCsummary()+"\",\"ctitle\":\""+lectureVO.getCtitle()+"\"}"); //设定通知的扩展属性。(注意 : 该参数要以 json map 的格式传入,否则会解析出错)
            ArticleVO articleVO = this.iArticleService.findOneById(item.getIlinkid());
            String url = articleVO.getCurl();
            String type = "";
            String videourl = "";
            String coverimg = "";
            String summary = articleVO.getCdesc();
            String title = articleVO.getCtitle();
            pushRequest.setAndroidExtParameters("{\"url\":\""+url+"\",\"type\":\""+type+"\",\"videourl\":\""+videourl+"\",\"coverimg\":\""+coverimg+"\",\"csummary\":\""+summary+"\",\"ctitle\":\""+title+"\"}"); //设定通知的扩展属性。(注意 : 该参数要以 json map 的格式传入,否则会解析出错)


//        // 推送控制
            Date pushDate = new Date(System.currentTimeMillis()); // 30秒之间的时间点, 也可以设置成你指定固定时间
            String pushTime = ParameterHelper.getISO8601Time(pushDate);
            pushRequest.setPushTime(pushTime); // 延后推送。可选，如果不设置表示立即推送
            String expireTime = ParameterHelper.getISO8601Time(new Date(System.currentTimeMillis() + 12 * 3600 * 1000)); // 12小时后消息失效, 不会再发送
            pushRequest.setExpireTime(expireTime);
            pushRequest.setStoreOffline(true); // 离线消息是否保存,若保存, 在推送时候，用户即使不在线，下一次上线则会收到


            PushResponse pushResponse = client.getAcsResponse(pushRequest);
            Log.info("RequestId: %s, MessageID: %s\n",
                    pushResponse.getRequestId(), pushResponse.getMessageId());
            item.setImessageid(pushResponse.getMessageId());
            item.setIrequestid(pushResponse.getRequestId());

            int count = this.pushmessageService.save(item);
            if (count > 0) {
                ajaxResult.setRetcode(1);
                ajaxResult.setRetmsg("操作成功！");
            } else {
                ajaxResult.setRetcode(0);
                ajaxResult.setRetmsg("操作失败！");
            }
        } catch (Exception e) {
            ajaxResult.setRetcode(0);
            ajaxResult.setRetmsg("操作失败！");
        }
        return ajaxResult;
    }


    @RequestMapping(value = "findAll")
    @ResponseBody
    public List<LectureVO> findAll(){
        List<LectureVO> lectureVOS = this.lectureService.findAll(null);
        return lectureVOS;
    }
    
    
    // 跳转到首页
    @RequestMapping(value = "/index")
    public ModelAndView index(HttpServletRequest request) {
        try {
            UserVO userVO = ClientManager.getInstance().getClient().getUser();
            HashMap<String, Object> model = new HashMap<String, Object>();
            if (null != userVO) {
               
                return new ModelAndView(this.viewPath + "/index", model);
            } else {
                return new ModelAndView("/mgr/login/index");
            }
        } catch (Exception e) {
            return new ModelAndView("/mgr/login/index");
        }
    }

}

